/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  ToolbarAndroid,
  Dimensions,
  Platform,
  BackHandler,
  ListView,
  DeviceEventEmitter,
  StatusBar
} from 'react-native';

import Common from '../../component/common';
import ScreenUtils from '../../component/ScreenUtils';
import ToolbarComponent from '../../component/ToolbarComponent';
import SubscriptionItem from './part/subscriptionItem';
import InfoItem from './part/infoItem';
import NewsItem from './part/newsItem';
import VarietyGroup from './part/varietyGroup';
import AppStorage from '../../component/appstorage';
import Loading from '../../component/loading';
import LoadError from '../../component/loadError';

const STATUS_BAR_HEIGHT = StatusBar.currentHeight || 20;


const totalWidth = Dimensions.get('window').width;
const HEADER_HEIGHT = totalWidth*0.112;


export default class collection extends Component {
  constructor(props) {
    super(props);
    this.state = {
    	dataSource: [],
		userToken: loginInfo.userToken,
		loading: true,
      	success: false,
      	errorMessage: '',
      	showInfoTitle:true,
      	refreshType:-1,
      	varietyData:new ListView.DataSource({
        	rowHasChanged: (row1, row2) => row1 !== row2,
      	}),
    };
    this.fetchData = this.fetchData.bind(this);
  }
  componentWillMount() {  
    if (Platform.OS === 'android') {  
      BackHandler.addEventListener('hardwareBackPress',() => Common.onBack(this));  
    }  
  }  
  componentWillUnmount() {
  	this.dealCollection.remove();
  	this.dealForward.remove();
    if (Platform.OS === 'android') {  
      BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this));  
    }  
  } 
  
  
 
  componentDidMount(){
  	/*ee3f7da0d0e20573af7dae6f3194ec18*/
  	this.dealCollection = DeviceEventEmitter.addListener('dealCollection',(data)=>{
  		this.refreshType = data ? parseInt(data) : -1;
  		this.fetchData(this.refreshType);
  	});
  	this.dealForward=this.props.navigator.navigationContext.addListener('didfocus',(newRouter)=>{
  		this.fetchData();
  		this.dealForward.remove();
  	})
  	
  }
	

  fetchData(dealType){
	let formData = new FormData();
	formData.append("userToken",this.state.userToken);
	this.showInfoTitle=true;
	Common.fetchData("POST", "/userCenter/collect/list", formData, (responseData) => {
		let changeData={type:-1,list:[]};
		let response=[];
		if(responseData.listResult.length>0){
			responseData.listResult.map((item,key)=>{
				if(parseInt(item.type)===4){
					this.showInfoTitle=false;
				}
				if(parseInt(item.type)===1 || parseInt(item.type)===2 || parseInt(item.type)===3){
					changeData.list.push(item)
				}else{
					response.push(item)
				}
			})
			response.push(changeData);
		}
		
		this.setState({
			dataSource: response,
			dataLength:response.length,
			showInfoTitle: this.showInfoTitle,
			loading: false,
			refreshType:dealType ? dealType : -1,
		    success: true,
		});
		
	},() => {
		this.setState({
			loading: false,
      		success: false,
      		errorMessage: '请求失败',
		});	        
	},() => {
		this.setState({
			loading: false,
	      	success: false,
	      	errorMessage: '网络错误',
		});
	});
  }
  
  
  render() {
    return (
      <View style ={styles.collectionContainer}>
  	    <ToolbarComponent
          leftItem={{
            title: 'Back',
            layout: 'icon',
            icon: require("../../images/back.png"),
            onPress: () => {
              Common.onBack(this);
            },
          }}
        >
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT} numberOfLines={1}>收藏</Text>
          </View>
        </ToolbarComponent>
      	{
      		this.state.loading ?
				<Loading/>
					: (
						this.state.success ?
							<ScrollView
					          keyboardDismissMode = "on-drag"
					    	  showsVerticalScrollIndicator ={false}
					    	  horizontal = {false}
					    	  style = {styles.scrollView}
					    	  removeClippedSubviews={ Platform.OS === 'android' ? true : false}
					      	>
							{
								this.state.dataLength == 0 ?
								<View style={styles.noCollection}>
									<Text>您还没有相关收藏</Text>
								</View> :
								<View style={styles.handlemargin}>
									{
									    this.state.dataSource.map((data,key)=>{
									        if(data.type === 8){
									          return(
									            <SubscriptionItem 
									              key={key}
									              data ={data.list}
									              chageThis = {this}
									              refreshType={this.state.refreshType}
									              showTitle={true} 
									              sectionTitle={data.typeName} 
									              userToken={this.state.userToken} 
									              showDeleteButton = {true}
									              classType={8} />
									          )
									        }else if (data.type === 5){
									          return(
									            <InfoItem 
									              key={key}
									              classType={5}
									              refreshType={this.state.refreshType}
									              data ={data.list} 
									              chageThis = {this} 
									              showTitle={this.state.showInfoTitle} 
									              sectionTitle={data.typeName}  
									              userToken={this.state.userToken} 
									              showDeleteButton = {true} />
									          )
									        }else if(data.type ===-1){
									          return(
									            <VarietyGroup 
									              key={key}
									              classType={-1} 
									              data ={data} 
									              refreshType={this.state.refreshType}
									              chageThis = {this} 
									              showTitle={true} 
									              userToken={this.state.userToken}  
									              showDeleteButton = {true}/>
									          )
									        }else if(data.type===4){
									          return(
									            <NewsItem
									              key={key}
									              classType={4} 
									              refreshType={this.state.refreshType}
									              data ={data} 
									              chageThis = {this} 
									              showTitle={true} 
									              userToken={this.state.userToken}  
									              showDeleteButton = {true}/>
									          ) 
									        }
									    })
									}
								</View>
							}	
							</ScrollView>
						    : <LoadError reload={this.fetchData} reason={this.state.errorMessage}/>
					)      		
      	}   		
      	
      </View>
    );
  }
}

const styles = StyleSheet.create({
  collectionContainer:{
    flex: 1,
  	backgroundColor:"#f6f6f6",
  	flexDirection:"column",
  },
  handlemargin:{
  	marginBottom:ScreenUtils.scaleSize(78),
  },
  toolbarV: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: 20
  },
  collectionCategory:{
  	paddingLeft:ScreenUtils.scaleSize(30),
  	fontSize:ScreenUtils.scaleSize(22),
  	color:"#939393",
  	paddingTop:ScreenUtils.scaleSize(14),
  },
  Item:{
  	marginTop:ScreenUtils.scaleSize(10),
  	borderTopWidth:1,
  	borderColor:"#ededed",
  },
  noCollection:{
  	flex:1,
  	height:Dimensions.get('window').height-HEADER_HEIGHT-STATUS_BAR_HEIGHT,
  	justifyContent: 'center',
    alignItems: 'center',
  },
    vItemContainer:{
    width:Dimensions.get('window').width,
  	backgroundColor:"#fff",
  	flexDirection:"row",
  	height:ScreenUtils.scaleSize(200),
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  	justifyContent:"center",
  	paddingLeft:ScreenUtils.scaleSize(30),
  	paddingRight:ScreenUtils.scaleSize(26),
  },
  vDescription:{
  	flex:1,
  	height:ScreenUtils.scaleSize(200),
  	flexDirection:"row",
  	alignItems:"center",
  },
  collectionCategory:{
  	paddingLeft:ScreenUtils.scaleSize(30),
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#939393",
  	paddingTop:ScreenUtils.scaleSize(14),
  },
  vDesImgWrap:{
  	width:ScreenUtils.scaleSize(110),
  	height:ScreenUtils.scaleSize(152),
  	justifyContent:"center",
  	alignItems:"center",
  },
  noImg:{
  	color:"#ededed",
  	fontSize:ScreenUtils.scaleSize(20),
  },
  vDesImg:{
  	width:ScreenUtils.scaleSize(110),
  	height:ScreenUtils.scaleSize(152),
  },
  vDesInfo:{
  	flex:1,
  	height:ScreenUtils.scaleSize(152),
  	flexDirection:"column",
  	justifyContent:"space-around",
  	paddingLeft:ScreenUtils.scaleSize(26),
  },
  vDesTitle:{
  	fontSize:ScreenUtils.scaleSize(30),
  	color:"#000",
  },
  vDesCategory:{
  	flexDirection:"row",
  },
  vDesCategoryItem:{
  	fontSize:ScreenUtils.scaleSize(18),
  	color:"#ff4545",
  	borderWidth:1,
  	borderColor:"#ff4545",
  	paddingLeft:5,
  	paddingRight:5,
  	marginRight:5,
  	borderRadius:4,
  },
  vBillBoard:{
  	fontSize:ScreenUtils.scaleSize(20),
  	color:"#000",
  },
  vIndex:{
  	width:ScreenUtils.scaleSize(200),
  	alignItems:"flex-end",
  	justifyContent:"center",
  	paddingRight:ScreenUtils.scaleSize(20),
  },
  vIndexTitle:{
  	color:"#d7d7d7",
  	fontSize:ScreenUtils.scaleSize(20),
  },
  varietyContent:{
  	flexDirection:"row",
  	alignItems:"center",
  },
  vIndexNum:{
  	fontSize:ScreenUtils.scaleSize(60),
  	color:"#ff4545",
  },
  deleteWrap:{
  	width:ScreenUtils.scaleSize(132),
  	backgroundColor:"#ff4545",
  	justifyContent:"center",
  	alignItems:"center",
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  },
  deleteText:{
  	fontSize:ScreenUtils.scaleSize(26),
  	color:"#fff",
  },
});